package org.kjtc.commom;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XmlSerializer<T> {

    public final String toTrim(final String strXml) {
        if (null == strXml || strXml.isEmpty()) {
            return "";
        }

        return strXml.substring(strXml.indexOf('<'));
    }

    @SuppressWarnings("unchecked")
    public final T unMarshallXml(final String xml, final Class<T> clas)
    throws JAXBException {
        if (xml.isEmpty()) {
            return null;
        }
        T object;

        JAXBContext jaxbContext = JAXBContext.newInstance(clas);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        String trimedXml = toTrim(xml);

        StringReader reader = new StringReader(trimedXml);

        object =  (T) unmarshaller.unmarshal(reader);

        return object;
    }

    @SuppressWarnings("unchecked")
    public final T unMarshallXml(File fileXml, final Class<T> clas)
    throws JAXBException {

        if (!fileXml.exists()) {
            return null;
        }
        T object;

        JAXBContext jaxbContext = JAXBContext.newInstance(clas);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        object =  (T) unmarshaller.unmarshal(fileXml);

        return object;
    }

    public final String marshallObj(
            final Class<T> clas, final T object, final String encoding)
    throws JAXBException {
        StringWriter sw = new StringWriter();

        JAXBContext context = JAXBContext.newInstance(clas);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        marshaller.marshal(object, sw);

        return sw.getBuffer().toString();
    }
}
